package org.gof.application.Clock
{
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	
	public class TimeClock extends BaseClock
	{
		// how many miliseconds have run before last Play.
		protected var runningTime: Number;
		
		protected var timeAtLastPlay:Number;
		
		protected var _ticksPerSecond:Number;
		protected var timer:Timer;
		
		public function TimeClock(ticksPerSecond:Number,notifies:Boolean)
		{
			this._ticksPerSecond = ticksPerSecond;	
			super(notifies);
			if (notifies)
			{
				timer = new Timer(1000/ticksPerSecond,0);
				timer.addEventListener(TimerEvent.TIMER,handleTimerEvent);
			}
		}
		private function handleTimerEvent(te:TimerEvent):void
		{
			tick();
		}
		public override function get ticks():Number
		{
			return (ms/1000 * _ticksPerSecond);	
		}
		
		public override function play():void
		{
			if (notifies)
			{
				timer.start();
			}
			timeAtLastPlay = now;
			super.play();
		}
		
		public override function pause():void
		{
			if (notifies)
			{
				timer.stop();
			}
			runningTime += (now - timeAtLastPlay);
		}
		public function get ticksPerSecond():Number
		{
			return this._ticksPerSecond;
		}
		protected function get ms():Number
		{
			 if (_playing)
			 {
			 	return (runningTime + (now - timeAtLastPlay));
			 } 
			return (runningTime);		
		}
		
		
		private function get now():Number
		{
			var d:Date = new Date();
			return d.time;
		}

	}
}